package org.boulderfoodrescue.webapp.client.old.viewer.scheduler;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.Format;

public class ShortTimeDateFormat implements Format{
  private static final String DATE_BOX_FORMAT_ERROR = "dateBoxFormatError";
  private final DateTimeFormat dateTimeFormat;
  
  /**
   * Creates a new expiration date format instance.
   */
  @SuppressWarnings("deprecation")
  public ShortTimeDateFormat(){
    dateTimeFormat = DateTimeFormat.getShortTimeFormat();
  }
  
  /**
   * Creates a new expiration date format instance.
   * 
     * @param dateTimeFormat the {@link DateTimeFormat} to use with this
     *          {@link Format}.
   */
  public ShortTimeDateFormat(DateTimeFormat dateTimeFormat){
    this.dateTimeFormat = dateTimeFormat;
  }
  
  @Override
  public String format(DateBox dateBox, Date date) {
    if(date == null){
      return "";
    } else {
      return dateTimeFormat.format(date);
    }
  }
  
  /**
     * Gets the date time format.
     *
     * @return the date time format
     */
  public DateTimeFormat getDateTimeFormat(){
    return dateTimeFormat;
  }
  
  @SuppressWarnings("deprecation")
  @Override
  public Date parse(DateBox dateBox, String text, boolean reportError) {
    Date date = null;
        try {
          if (text.length() > 0) {
            date = dateTimeFormat.parse(text);
          }
        } catch (IllegalArgumentException exception) {
          try {
            date = new Date(text);
          } catch (IllegalArgumentException e) {
            if (reportError) {
              dateBox.addStyleName(DATE_BOX_FORMAT_ERROR);
            }
            return null;
          }
        }
        return date;
  }

  @Override
  public void reset(DateBox dateBox, boolean abandon) {
    dateBox.removeStyleName(DATE_BOX_FORMAT_ERROR);
  }
}